package com.thinkTank.oa.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.thinkTank.oa.common.UserInfo;
import com.thinkTank.oa.entity.DemandData;
import com.thinkTank.oa.entity.Memo;
import com.thinkTank.oa.entity.Permission;
import com.thinkTank.oa.entity.Subscribe;
import com.thinkTank.oa.entity.User;
import com.thinkTank.oa.service.DemandDataService;
import com.thinkTank.oa.service.DetailsService;
import com.thinkTank.oa.service.MemoService;
import com.thinkTank.oa.service.PermissionService;
import com.thinkTank.oa.service.SubscribeService;
import com.thinkTank.oa.service.UserService;
import com.thinkTank.oa.util.StrUtil;
import com.thinkTank.oa.util.MD5Util;
import com.thinkTank.oa.util.VerifyCodeUtils;



@Controller
public class LoginController  extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private DetailsService detailsService;
	@Resource
	private PermissionService permissionService;

	@Resource
	private UserService userService;

	@Autowired
	private MemoService memoService;
	@Autowired
	private DemandDataService demandDataService;
	/***
	 * 显示登录页面
	 * @date 2018-08-09
	 * @author dq
	 * @param request
	 * @return
	 */
	@ RequestMapping(value= "login")
	public String login(HttpServletRequest request){
		if(null!=getUserInfoBySession(request)){
			return index(1,request);
		}else{
			return "login";
		}
		
	}
	/***
	 * 显示首页
	 * @date 2018-08-09
	 * @author dq
	 * @param request
	 * @return
	 */
	@ RequestMapping(value= "index")
	public String index(Integer pageNo,HttpServletRequest request){
	
		//System.out.println("跳转到 index页面");
		/**
		 * 查询当前用户正在对接的任务
		 */
		if(null==pageNo){
			pageNo=1;
		}
		 String userId =this.getUserId(request);
		//List<Dictiontry> buttStatus=SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
		//request.setAttribute("buttStatus", buttStatus);
		
//		 PageHelper.startPage(pageNo, DEFAULT_COUNT);
//		 String userId =this.getUserId(request);
//		 List<ButtDetails> buttDetails =detailsService.findButtDetailsByUserId(userId);
//		 PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(buttDetails);
//		 request.setAttribute("pageInfo", pageInfo);
		 PageHelper.startPage(pageNo, 6);
		List<Subscribe> subList = subscribeService.findAllSubByUserId(userId);
		PageInfo<Subscribe> pageInfo = new PageInfo<Subscribe>(subList);
		 request.setAttribute("pageInfo", pageInfo);
		//分组查询当前用户任务数量
		
		 List<Map<Object,Object>> buttGroupCount = detailsService.findButtDetailsGoupbyStatus(userId);
		 Map<Object,Object> count=new HashMap<Object,Object>();
		 for(Map<Object,Object> temp:buttGroupCount){
			 
			 count.put(temp.get("buttstatus"), temp.get("count"));
		 }
		 request.setAttribute("count", count);
		 
			List<Permission> per=permissionService.queryAllUserByPerm(userId);
			request.getSession().setAttribute("userMenu", per);		 
		 
		 //查询用户的备忘录
		 List<Memo> memoList = memoService.queryAll(Memo.create(userId));
		 request.setAttribute("memoList", memoList);
		return "index";
	}
	
	/***
	 * 修改密码
	 * @date 2018-10-26
	 * @author dq
	 * @return
	 */
	@RequestMapping(value= "showUpdatePwd")
	public String  showUpdatePwd(HttpServletRequest request){
		try{
			/* UserInfo userinfo =getUserInfoBySession(request);
			if(null!=userinfo){
				
			}*/
		}catch(Exception e){
			
		}
		return "showUpdatePwd";
	}
	/***
	 * 修改密码
	 * @date 2018-10-26
	 * @author dq
	 * @return
	 */
	@RequestMapping(value= "updatePwd")
	public String  updatePwd(HttpServletRequest request,String pwd1,String pwd2,String pwd3){
		String msg="";
		try{
			 UserInfo userinfo =getUserInfoBySession(request);
			 
			if(null!=userinfo){
				if(null!=pwd1&&null!=pwd2&&null!=pwd3&&pwd2.equals(pwd3)&&pwd2.length()>10){
					User user =userService.findUserById(userinfo.getUserId());
					if(user.getMd5().equals(MD5Util.MD5(pwd1))){
						user.setMd5(MD5Util.MD5(pwd2));
						userService.update(user);
						msg="修改密码成功";
					}
				}else{
					msg="密码格式错误或原始密码错误";
				}
			}else{
				msg="当前用户不存在";
			}
		}catch(Exception e){
			
		}
		request.setAttribute("msg", msg);
		return "showUpdatePwd";
	}
	
	/**
	 * 退出当前登录
	 * @date 2018-08-09
	 * @author dq
	 * @param request
	 * @return
	 */
	@ RequestMapping(value= "loginOut")
	public  String loginOut(HttpServletRequest request, HttpServletResponse response){
		 Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		    if (auth != null){   
		    	
				for (Cookie cookie : request.getCookies()) {
					// 从 cookie 中取
					if ("remember-me".equals(cookie.getName())) {
						try {
							
							Cookie cookied = new Cookie("remember-me", "");
							response.addCookie(cookied);
						} catch (Exception e) {
							return null;
						}
					}
				}
		       new SecurityContextLogoutHandler().logout(request, response, auth);
		    }
		return "redirect:/login?logout";
	}

		@RequestMapping("/")
		public String index_we( HttpServletRequest request,HttpServletResponse response) {
			try{
				if(null!=getUserInfoBySession(request)){
					return index(1,request);
				}else{
					UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
							.getPrincipal();
					if(userDetails!=null){
						return index(1,request);
					}else{
						return "login";
					}
					
				}
			}catch(Exception e){
				return "login";
			}
		
			
		}
	
		@RequestMapping("/showAddDemand")
		public String showAddDemand(){
			
			return "addDemand";
		}
		@RequestMapping("/addDemand")
		public String addDemand(Integer attr_project_type, String attr_name,String attr_company,
				String	attr_phone,	String	attr_email,	String	attr_projectName, String txt,
				HttpServletRequest request,HttpSession session){
			try{
				//验证验证码
				String code = request.getParameter("captchas");
		    	Object verCode = session.getAttribute("verCode");
		    	if (null == verCode) {
		    		request.setAttribute("errmsg", "验证码已失效，请重新输入");
		    		return "验证码已失效，请重新输入";
		    	}
		    	String verCodeStr = verCode.toString();
		    	LocalDateTime localDateTime = (LocalDateTime)session.getAttribute("codeTime");
		    	long past = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
		    	long now = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
		    	if(verCodeStr == null || code == null || code.isEmpty() || !verCodeStr.equalsIgnoreCase(code)){
		    		request.setAttribute("errmsg", "验证码错误");
		    		return showAddDemand();
		    	} else if((now-past)/1000/60>5){
		    		request.setAttribute("errmsg", "验证码已过期，重新获取");
		    		 return showAddDemand();
		    	} else {
		    		//验证成功，删除存储的验证码
		    		session.removeAttribute("verCode");
		    		
		    		DemandData demandData = new DemandData();
		    		demandData.setDemandType(attr_project_type);
		    		demandData.setDemandDate(StrUtil.getCurrentDateTime_two());
		    		demandData.setDemandName(attr_name);
		    		demandData.setJigou(attr_company);
		    		demandData.setTell(attr_phone);
		    		demandData.setDemandTitle(txt);
		    		demandData.setEmail(attr_email);
		    		demandData.setName(attr_projectName);
		    		
		    		demandDataService.add(demandData);
		    		return "addsuccess";
		    	}

			}catch(Exception e){
				e.printStackTrace();
			}
			return "addsuccess";
		}
		@RequestMapping(value="/getImage",method=RequestMethod.GET)
	    public void authImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("image/jpeg");
			// 生成随机字串
			String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
			// 存入会话session
			HttpSession session = request.getSession(true);
			// 删除以前的
			session.removeAttribute("verCode");
			session.removeAttribute("codeTime");
			session.setAttribute("verCode", verifyCode.toLowerCase());
			session.setAttribute("codeTime", LocalDateTime.now());
			// 生成图片
			int w = 100, h = 30;
			OutputStream out = response.getOutputStream();
			VerifyCodeUtils.outputImage(w, h, out, verifyCode);
	    }
		
		
		@RequestMapping("/addMemo")
		@ResponseBody
		public String addMemo(Memo memo, HttpServletRequest request) {
			memo.setPid(StrUtil.getUUID32());
			memo.setUserId(getUserId(request));
			memoService.add(memo);
			return "success";
		}
		
		@RequestMapping("/updateMemo")
		@ResponseBody
		public String updateMemo(Memo memo, HttpServletRequest request) {
			memo.setUserId(getUserId(request));
			memoService.update(memo);
			return "success";
		}
		
		@RequestMapping("/deleteMemo")
		@ResponseBody
		public String deleteMemo(String memoId) {
			memoService.delete(memoId);
			return "success";
		}
		
		@RequestMapping("/clearMemo")
		@ResponseBody
		public String clearMemo(HttpServletRequest request) {
			memoService.clear(getUserId(request));
			return "success";
		}
		
		@RequestMapping("/refresh")
		public String refresh(String taskTime, @RequestParam(defaultValue="1") Integer pageNo, HttpServletRequest request) {
			return index(pageNo, request);
		}
		     /**
		       * 判断用户是否从Remember Me Cookie自动登录
		       * @return
		     
		      private boolean isRememberMeAuthenticated() {
		 
		          Authentication authentication = SecurityContextHolder.getContext()
		                 .getAuthentication();
		          if (authentication == null) {
		             return false;
		         }
		 
		         return RememberMeAuthenticationToken.class
		                 .isAssignableFrom(authentication.getClass());
		     } */
}
